package controller;

import dao.Impl.empchange;
import entity.Employee;
import entity.EmployeeChange;
import entity.Organization;
import entity.SalaryStandard;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;
import service.Impl.EmployeeChangeServiceImpl;
import service.Impl.EmployeeServiceImpl;
import service.Impl.OrganizationServiceImpl;
import service.Impl.SalaryStandardServiceImpl;

import javax.servlet.http.HttpSession;
import java.util.Date;
import java.util.List;

@Controller
@RequestMapping("hr")
public class hrcontroller {
    @Autowired
    SalaryStandardServiceImpl salaryStandardServiceImpl;
    @Autowired
    private EmployeeServiceImpl employeeService;
    @Autowired
    private OrganizationServiceImpl organizationService;
    @Autowired
    private empchange empchange;
    @Autowired
    private EmployeeChangeServiceImpl employeeChangeServiceImpl;
    @GetMapping("/employee/list")
    public String listEmployees(Model model, HttpSession session) {
        Employee loginUser = (Employee) session.getAttribute("loginUser");
        if (loginUser == null) {
            return "redirect:/auth/login";
        }

        // 检查权限

        if (!(loginUser.getEmpRole()==2||loginUser.getEmpRole()==1||loginUser.getEmpRole()==5)) {
            model.addAttribute("error", "没有权限访问此页面");
            return "redirect:/auth/index";
        }

        // 获取所有员工列表
        List<Employee> employees = employeeService.findAll();
        model.addAttribute("employees", employees);

        // 获取所有部门列表（用于添加员工时选择）
        List<Organization> organizations = organizationService.findAll();
        model.addAttribute("organizations", organizations);

        return "hr/employee/list";
    }


    @GetMapping("/employee/add")
    public String toAddEmployee(Model model, HttpSession session, RedirectAttributes redirectAttributes) {
        // 检查权限
        Employee loginUser = (Employee) session.getAttribute("loginUser");
        if (loginUser == null) {
            return "redirect:/auth/login";
        }
        if (!(loginUser.getEmpRole()==1||loginUser.getEmpRole()==2||loginUser.getEmpRole()==5)) {
            model.addAttribute("error", "没有权限访问此页面");
            return "redirect:/hr/employee/list";
        }

        // 获取部门列表
        List<Organization> organizations = organizationService.findAll();
        model.addAttribute("organizations", organizations);

        // 获取薪酬标准列表
        List<SalaryStandard> salaryStandards = salaryStandardServiceImpl.findAll();
        model.addAttribute("salaryStandards", salaryStandards);

        return "hr/employee/add";
    }

    /**
     * 处理添加员工请求
     */
    @PostMapping("/employee/add")
    public String handleAddEmployee(@ModelAttribute Employee employee,
                                    @RequestParam Long orgId,
                                    @RequestParam Long salaryStandardId,
                                    @RequestParam String confirmPassword,
                                    Model model,
                                    HttpSession session,
                                    RedirectAttributes redirectAttributes) {
        // 检查权限
        Employee loginUser = (Employee) session.getAttribute("loginUser");
        if (loginUser == null) {
            return "redirect:/auth/login";
        }
        if (!(loginUser.getEmpRole()==1||loginUser.getEmpRole()==2||loginUser.getEmpRole()==5)) {
            model.addAttribute("error", "没有权限访问此页面");
            return "redirect:/hr/employee/list";
        }

        // 验证密码是否一致
        if (!employee.getEmpPassword().equals(confirmPassword)) {
            model.addAttribute("error", "两次输入的密码不一致");
            model.addAttribute("organizations", organizationService.findAll());
            model.addAttribute("salaryStandards", salaryStandardServiceImpl.findAll());
            return "hr/employee/add";
        }

        try {
            // 设置员工初始状态为在职
            employee.setEmpStatus(1);
            employee.setEmpCreateTime(new Date());
            employee.setEmpUpdateTime(new Date());
            employee.setOrgId(orgId);
            employee.setSalaryStandardId(salaryStandardId);
            // 添加员工
           empchange.create(employee);
           EmployeeChange employeeChange = new EmployeeChange();
           employeeChange.setEmpId(employee.getEmpId());
           employeeChange.setCreateUserId(loginUser.getEmpId());
           employeeChange.setCreateTime(new Date());
           employeeChange.setReviewStatus(0);
           Boolean a=employeeChangeServiceImpl.create(employeeChange);


            if (a) {

                redirectAttributes.addFlashAttribute("success", "员工添加成功");
                return "redirect:/hr/employee/list";
            } else {
                throw new RuntimeException("添加员工失败");
            }
        } catch (Exception e) {
            model.addAttribute("error", "添加员工失败：" + e.getMessage());
            model.addAttribute("organizations", organizationService.findAll());
            model.addAttribute("salaryStandards", salaryStandardServiceImpl.findAll());
            return "hr/employee/add";
        }
    }

    @GetMapping("/employee/detail/{empId}")
    public String employeeDetail(@PathVariable Long empId, Model model, HttpSession session) {
        // 检查权限
        Employee loginUser = (Employee) session.getAttribute("loginUser");
        if (loginUser == null) {
            return "redirect:/auth/login";
        }
        if (!(loginUser.getEmpRole()==1||loginUser.getEmpRole()==2||loginUser.getEmpRole()==5)) {
            model.addAttribute("error", "没有权限访问此页面");
            return "redirect:/hr/employee/list";
        }
        // 获取员工信息
        Employee employee = employeeService.findById(empId);
        if (employee == null) {
            model.addAttribute("error", "员工不存在");
            return "redirect:/hr/employee/list";
        }

        // 获取部门信息
        Organization org = organizationService.findById(employee.getOrgId());
        ////
        model.addAttribute("employee", employee);
        model.addAttribute("organization", org);
        return "hr/employee/detail";
    }

    @GetMapping("/employee/terminate/{empId}")
    public String toTerminateEmployee(@PathVariable Long empId, HttpSession session, Model model) {
        // 检查权限
        Employee loginUser = (Employee) session.getAttribute("loginUser");
        if (loginUser == null) {
            return "redirect:/auth/login";
        }
        if (!(loginUser.getEmpRole()==1||loginUser.getEmpRole()==2||loginUser.getEmpRole()==5)) {
            model.addAttribute("error", "没有权限访问此页面");
            return "redirect:/hr/employee/list";
        }

        // 获取员工信息
        Employee employee = employeeService.findById(empId);
        EmployeeChange employeeChange = new EmployeeChange();

        if (employee == null) {
            model.addAttribute("error", "员工不存在");
            return "redirect:/hr/employee/list";
        }
        // 检查员工状态
        if (!employee.isActive()) {
            model.addAttribute("error", "该员工已离职");
            return "redirect:/hr/employee/list";
        }
          employee.setEmpStatus(0);
       if(!empchange.deleteById(employee.getEmpId())){
           empchange.create(employee);
       }
        else{empchange.create(employee);}
        employeeChange.setEmpId(employee.getEmpId());
        employeeChange.setCreateUserId(loginUser.getEmpId());
        employeeChange.setCreateTime(new Date());
        employeeChange.setReviewStatus(0);

        if(!employeeChangeServiceImpl.deleteById(employee.getEmpId())){
            employeeChangeServiceImpl.create(employeeChange);
        }
       else{ employeeChangeServiceImpl.create(employeeChange);}
        model.addAttribute("success","离职申请成功");
        return "hr/employee/list";
    }


}
